package homework1_3;

import java.io.IOException;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.List;

/**
 * 服务器类
 */
public class Server {
    private static List<Socket> sockets = new ArrayList<>();//创建一个集合存储客户端的socket
    private static ServerSocket ss = null;
    private static Socket s = null;
    public static void main(String[] args) {
        server();
    }
    //连接客户端开始服务
    public static void server(){
        while (true){
            try {
                ss =  new ServerSocket(8000);
                System.out.println("等待连接ing");
                s= ss.accept();//接收客户端的连接并赋值给Socket
                sockets.add(s);
                System.out.println("客户端"+s.getInetAddress()+"连接成功");
                //每连接一个客户使用一个线程为之服务
                new ServerThread(sockets,s).start();
            } catch (IOException e) {
                e.printStackTrace();
            } finally {

                if (null !=ss){
                    try {
                        ss.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }
}
